from datetime import datetime, timedelta

from django.db import transaction
from rest_framework import generics
from rest_framework.views import APIView
from utils.permissions import IsMemberUser
from utils import response_error, response_ok
from utils.exception import CustomError
from utils.customer_modelviewset import CustomModelViewSet
from apps.system.models import Upload
from apps.member.models import MemberRecord
from .serializers import DiaryDetailSerializer
from .models import Diary


class DiaryCollectViewSet(APIView):
    # 收藏
    permission_classes = (IsMemberUser,)

    def get(self, request, id):
        diary = Diary.objects.filter(pk=id).first()
        if not diary:
            return response_error('为找到对应的日志')

        member_record = MemberRecord.objects.filter(content_type=Diary.get_content_type(), object_id=id,
                                                    user=self.request.user, operate=MemberRecord.COLLECT).first()
        with transaction.atomic():
            if member_record:
                # 存在，删除
                diary.collect_count -= 1
                diary.save()
                member_record.delete()
                return response_ok()
            # 不存在，创建
            diary.collect_count += 1
            diary.save()
            MemberRecord.objects.create(content_object=diary, user=self.request.user, operate=MemberRecord.COLLECT,
                                        describe='收藏')
        return response_ok()


class DiarylikeViewSet(APIView):
    '''点赞'''
    permission_classes = (IsMemberUser,)

    def get(self, request, id):
        diary = Diary.objects.filter(pk=id).first()
        if not diary:
            return response_error('为找到对应的日志')

        with transaction.atomic():

            member_record = MemberRecord.objects.filter(content_type=Diary.get_content_type(), object_id=id,
                                                        user=self.request.user, operate=MemberRecord.LIKE).first()
            if member_record:
                # 存在，删除
                diary.like_count -= 1
                diary.save()
                member_record.delete()
                return response_ok()
            # 不存在，创建
            diary.like_count += 1
            diary.save()
            MemberRecord.objects.create(content_object=diary, user=self.request.user, operate=MemberRecord.LIKE,
                                        describe='点赞')
        return response_ok()


class DiaryDetailViewSet(generics.RetrieveAPIView):
    # 详情
    queryset = Diary.objects.filter(delete=False)
    serializer_class = DiaryDetailSerializer

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()

        with transaction.atomic():
            instance.browse_count += 1
            instance.save()
            # 保存浏览记录，
            if self.request.user and self.request.user.is_authenticated:
                member_record = MemberRecord.objects.filter(content_type=Diary.get_content_type(),
                                                            object_id=instance.id,
                                                            user=self.request.user,
                                                            operate=MemberRecord.BROWSE).first()
                # 同一人短时间内浏览不做记录
                if not member_record or (datetime.now() - member_record.create_time).days > 0:
                    MemberRecord.objects.create(content_object=instance, user=self.request.user,
                                                operate=MemberRecord.BROWSE, describe='浏览')
                else:
                    # 同一天，更新创建时间
                    if member_record:
                        member_record.create_time = datetime.now()
                        member_record.save()

        return super(DiaryDetailViewSet, self).retrieve(request, *args, **kwargs)


class DiaryHotViewSet(generics.ListAPIView):
    '''热帖'''
    queryset = Diary.objects.filter(delete=False).order_by('-browse_count', '-like_count')
    serializer_class = DiaryDetailSerializer


class DiaryViewSet(CustomModelViewSet):
    '''个人日志的增删查'''
    permission_classes = (IsMemberUser,)
    queryset = Diary.objects.filter(delete=False)
    serializer_class = DiaryDetailSerializer

    def filter_queryset(self, queryset):
        queryset = queryset.filter(user=self.request.user)
        return queryset

    def create(self, request, *args, **kwargs):
        try:
            content = request.data['content']
            img_id = request.data['img_id']  # 封面图

            with transaction.atomic():
                if img_id:
                    image = Upload.objects.filter(pk=img_id).first()
                    if image:
                        diary = Diary.objects.create(content=content, user=request.user, image=image)
                        MemberRecord.objects.create(content_object=diary, user=self.request.user, operate=MemberRecord.INSERT,
                                            describe='发布了一篇日记')
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))

        return response_ok()

    def destroy(self, request, *args, **kwargs):
        try:
            with transaction.atomic():
                diary = self.get_object()
                diary.delete = True
                diary.save()
        except Exception as e:
            return response_error(str(e))
        return response_ok()
